package com.alennus.blog.nio.channel;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * Created by pactera on 2018/9/26.
 *
 * Java NIO的通道类似流，但又有些不同：

 既可以从通道中读取数据，又可以写数据到通道。但流的读写通常是单向的。
 通道可以异步地读写。
 通道中的数据总是要先读到一个Buffer，或者总是要从一个Buffer中写入。
 *
 */
public class Channel {

//使用FileChannel读取数据到Buffer中
    public static void main(String[] args){
        String fileAddress = "D:\\logs\\spring-boot-logging.log";
        Path path1 = Paths.get(fileAddress);
        System.out.println("path1 = " + path1);

        Path path2 = path1.normalize();
        System.out.println("path2 = " + path2);
        try {
            RandomAccessFile randomAccessFile = new RandomAccessFile(path1.toString(),"rw");
            FileChannel fileChannel = randomAccessFile.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1048);

            int bytesRead = fileChannel.read(byteBuffer);
            while (bytesRead != -1) {
                System.out.println("Read " + bytesRead);
                // buf.flip() 的调用，首先读取数据到Buffer，然后反转Buffer,接着再从Buffer中读取数据
                byteBuffer.flip();
                while(byteBuffer.hasRemaining()){
                    System.out.print((char) byteBuffer.get());
                }
                byteBuffer.clear();
                bytesRead = fileChannel.read(byteBuffer);
            }
            randomAccessFile.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
